import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
import { useRoute, useRouter } from 'vue-router';
import { formatAxis } from '/@/utils/formatTime';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { NextLoading } from '/@/utils/loading';
import { useDictsStore } from '/@/stores/dicts';

export function useLoginSuccess() {
  const router = useRouter();
  const route = useRoute();
  const dictsStore = useDictsStore();

  const signInSuccess = (isNoPower?: boolean) => {
    if (isNoPower) {
      ElMessage.warning('抱歉，您没有登录权限');
      Session.clear();
    } else {
      // 初始化登录成功时间问候语
      let currentTimeInfo = formatAxis(new Date());
      // 登录成功，跳到转首页
      // 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
      if (route.query?.redirect) {
        router.push({
          path: <string>route.query?.redirect,
          query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
        });
      } else {
        router.push('/');
      }
      // 登录成功提示
      const signInText = '欢迎回来';
      ElMessage.success(`${currentTimeInfo}，${signInText}`);
      // 添加 loading，防止第一次进入界面时出现短暂空白
      NextLoading.start();
    }
  };

  return async (token: string) => {
    Session.set('token', token);
    // 前端控制路由，2、请注意执行顺序
    const isNoPower = await initFrontEndControlRoutes();
    signInSuccess(isNoPower);
  };
}
